package com.skt.utils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * 日志过滤器 - 用于设置请求追踪ID
 */
@Slf4j
@Component
@Order(1)
public class LogFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        // 生成追踪ID
        String traceId = generateTraceId((HttpServletRequest) request);
        MDC.put("traceId", traceId);

        // 记录请求开始日志
        long startTime = System.currentTimeMillis();
        ((HttpServletRequest) request).setAttribute("startTime", startTime);

        if (log.isDebugEnabled()) {
            log.debug("请求开始: {} {}",
                    ((HttpServletRequest) request).getMethod(),
                    ((HttpServletRequest) request).getRequestURI());
        }

        try {
            chain.doFilter(request, response);
        } finally {
            // 记录请求完成日志
            long endTime = System.currentTimeMillis();
            long costTime = endTime - startTime;

            if (log.isDebugEnabled()) {
                log.debug("请求完成: {} {} - 耗时: {}ms",
                        ((HttpServletRequest) request).getMethod(),
                        ((HttpServletRequest) request).getRequestURI(),
                        costTime);
            }

            // 慢请求警告
            if (costTime > 1000) {
                log.warn("慢请求警告: {} {} - 耗时: {}ms",
                        ((HttpServletRequest) request).getMethod(),
                        ((HttpServletRequest) request).getRequestURI(),
                        costTime);
            }

            // 清理MDC - 使用修复后的方法
            MDC.clear();
        }
    }

    /**
     * 生成追踪ID
     */
    private String generateTraceId(HttpServletRequest request) {
        String traceId = request.getHeader("X-Trace-Id");
        if (traceId == null || traceId.trim().isEmpty()) {
            traceId = "TRACE-" + UUID.randomUUID().toString().substring(0, 8);
        }
        return traceId;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("日志过滤器初始化完成");
    }

    @Override
    public void destroy() {
        log.info("日志过滤器销毁");
    }
}